const {baseConfig} = require("./config");

function start(app) {
    const http = require("http").Server(app);


    const fs = require("fs");
    const path = require("path");
    const cors = require("cors");
    const express = require("express");
    require('express-async-errors');
    const router = express.Router();
    const {autoImportRoutes, formatResponse} = require('./utils/util')
    var bodyParser = require("body-parser");
    const {baseConfig} = require("./config");
    // 跨域设置
    app.use(cors());

    // 解析请求体中的 JSON 数据
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: true}));

    // 设置静态文件目录
    app.use(express.json());
    app.use(express.static("../client"));


    // 路由设置
    app.use(formatResponse);

    // 路由自动导入
    autoImportRoutes(app, path.join(__dirname, './router'));

    // 全局错误处理中间件
    app.use((err, req, res, next) => {
        console.error(err.stack);
        res.apiError(err.message, [])
    });

    app.listen(baseConfig.SERVER_PORT, () => {
        console.log(`Server is running on http://localhost:${baseConfig.SERVER_PORT};`)
    });

    // 关于socketio的操作 聊天socket
    // app.use(express.static('../client'))
    const socket = require('./socket/index')
    socket(http)


}

module.exports = start